<template>
	<view class="container">
		<!-- 蓝色背景区域 -->
		<view class="blue-bg"></view>
		
		<!-- 内容区域 -->
		<view class="content">
			<!-- 地图卡片 -->
			<view class="map-card">
				<view class="map-wrapper">
					<map 
						id="map"
						class="map"
						:latitude="latitude"
						:longitude="longitude"
						:markers="allMarkers"
						:scale="14"
						show-location
						@markertap="onMarkerTap"
						@callouttap="onMarkerTap"
						@regionchange="onMapRegionChange"
					></map>
				</view>
			</view>
		</view>

		<!-- 店铺信息弹窗 -->
		<view class="shop-popup" v-if="showShopInfo">
			<view class="shop-info">
					<view class="shop-content">
						<view class="shop-header">
							<text class="shop-name">{{currentShop.name}}</text>
							<text class="shop-distance">{{currentShop.distance}}</text>
						</view>
						<view class="rating">
							<uni-rate 
								:value="currentShop.score" 
								:size="16" 
								:readonly="true"
								:allow-half="true"
								active-color="#FFB700"
								:margin="2"
							/>
							<text class="score">{{Math.floor(currentShop.score)}}分</text>
						</view>
						<view class="shop-info-item">营业时间：{{currentShop.businessHours}}</view>
						<view class="shop-info-item">位置：{{currentShop.address}}</view>
						<image class="shop-image" :src="currentShop.image" mode="aspectFill"></image>
					</view>
				
				
				<view class="action-buttons">
					<button class="contact-btn" @click="contactShop">
						<image class="btn-icon" src="/static/电话@2x.png" mode="aspectFit"></image>
						联系门店
					</button>
					<button class="book-btn" @click="bookService">
						<image class="btn-icon" src="/static/预约@2x.png" mode="aspectFit"></image>
						立即预定
					</button>
				</view>
			</view>
		</view>

		<!-- 呼叫弹窗 -->
		<view class="call-popup" v-if="showCallPopup">
			<view class="call-content">
				<view class="phone-number" @click="handleCall">{{currentShop.phone}}</view>
				<view class="action-list">
					<view class="action-item" @click="handleCopy">复制</view>
					<view class="action-item cancel" @click="handleCancel">取消拨号</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
// 导入高德地图工具类和位置服务工具类
import amap from '@/utils/amap.js'
import locationService from '@/utils/location.js'

export default {
	data() {
		return {
			// 默认地图中心点坐标
			latitude: 35.234850,
			longitude: 113.248600,
			
			// 控制店铺信息弹窗显示
			showShopInfo: true,
			
			// 地图标记点数组（不包含用户位置标记）
			markers: [],
			
			// 维修店列表数据
			shops: [
				{
					id: 1,
					latitude: 35.238850,
					longitude: 113.252600,
					name: '车百事汽车生活馆',
					image: '/static/index_活动2.png',
					businessHours: '周一至周五 早上8:00-晚上22:00',
					address: '山阳区人民路与解放路交叉口',
					distance: '1.2km',
					score: 4.5,
					phone: '0391-3568899'
				},
				{
					id: 2,
					latitude: 35.239850,
					longitude: 113.249600,
					name: '安达汽车维修中心',
					image: '/static/index_活动2.png',
					businessHours: '周一至周日 早上9:00-晚上21:00',
					address: '山阳区太行路与人民路交叉口',
					distance: '1.5km',
					score: 3.8,
					phone: '0391-3566688'
				},
				{
					id: 3,
					latitude: 35.231850,
					longitude: 113.245600,
					name: '车之家汽修店',
					image: '/static/index_活动2.png',
					businessHours: '周一至周六 早上8:30-晚上20:30',
					address: '山阳区解放路与建设路交叉口',
					distance: '1.8km',
					score: 4.2,
					phone: '0391-3567788'
				},
				{
					id: 4,
					latitude: 35.241850,
					longitude: 113.243600,
					name: '鑫源汽车服务中心',
					image: '/static/index_活动2.png',
					businessHours: '周一至周日 早上8:00-晚上23:00',
					address: '山阳区新华路与建设路交叉口',
					distance: '2.1km',
					score: 2.5,
					phone: '0391-3565599'
				}
			],

			// 用户位置标记配置
			userLocationMarker: {
				id: 998,
				latitude: 0,
				longitude: 0,
				iconPath: '/static/椭圆 3 拷贝 2@2x.png',
				width: 24,
				height: 34,
				anchor: {x: 0.5, y: 0.5}, // 图标锚点，决定图标与经纬度的对应点
				zIndex: 1 // 层级，确保在其他标记下方
			},

			// 用户位置提示标记配置
			userTipMarker: {
				id: 999,
				latitude: 0,
				longitude: 0,
				iconPath: '/static/矩形 5 拷贝@2x.png',
				width: 120,
				height: 40,
				anchor: {x: 0.5, y: 1.2},
				zIndex: 2,
				callout: {
					content: '附近门店 >',
					color: '#ffffff',
					display: 'ALWAYS',
					textAlign: 'center',
					fontSize: 14,
					anchorX: 0,
					anchorY: 30,
					bgColor: 'transparent'
				}
			},

			// 当前选中的店铺信息
			currentShop: {
				name: '车百事汽车生活馆',
				image: '/static/index_活动2.png',
				businessHours: '周一至周五 早上8:00-晚上22:00',
				address: '山阳区人民路与解放路交叉口',
				distance: '556m',
				score: 4.5,
				phone: '0391-3568899'
			},

			showCallPopup: false,  // 控制呼叫弹窗显示
			selectedMarkerId: null  // 当前选中的标记点ID
		}
	},

	computed: {
		// 合并所有标记点（包括用户位置标记和店铺标记）
		allMarkers() {
			return [...this.markers, this.userLocationMarker, this.userTipMarker]
		}
	},

	// 页面加载时，如果传递了经纬度，则使用传递的经纬度，否则使用默认位置
	onLoad(options) {
		if (options.latitude && options.longitude) {
			// 使用传入的位置参数
			this.latitude = parseFloat(options.latitude);
			this.longitude = parseFloat(options.longitude);
			this.updateLocation({
				latitude: this.latitude,
				longitude: this.longitude
			});
			this.initDefaultShop();
		} else {
			// 获取当前位置
			this.initLocation();
		}
	},

	methods: {
		// 初始化位置信息
		async initLocation() {
			try {
				// 获取当前位置
				const location = await locationService.getCurrentLocation();
				this.updateLocation(location);
				// 获取位置后初始化默认选中状态
				this.initDefaultShop();
			} catch (err) {
				console.error('初始化位置失败:', err);
				// 使用默认位置
				this.updateLocation({
					latitude: this.latitude,
					longitude: this.longitude
				});
				uni.showToast({
					title: '定位失败，使用默认位置',
					icon: 'none'
				});
				// 使用默认位置也要初始化默认选中状态
				this.initDefaultShop();
			}
		},

		// 初始化默认选中的店铺
		initDefaultShop() {
			if (this.shops.length > 0) {
				// 默认选中第一个店铺
				this.selectedMarkerId = this.shops[0].id;
				this.currentShop = this.shops[0];
				this.showShopInfo = true;
				this.updateShopMarkers();  // 更新标记以显示选中状态
			}
		},
		updateUserLocation(latitude, longitude) {
			// 只更新用户位置标记和提示框
			this.userLocationMarker.latitude = latitude
			this.userLocationMarker.longitude = longitude
			
			// 调整矩形框位置，使其在用户位置正上方
			this.userTipMarker.latitude = latitude + 0.0004
			this.userTipMarker.longitude = longitude
		},
		updateLocation(location) {
			// 初始化时设置地图中心点和用户位置
			this.latitude = location.latitude
			this.longitude = location.longitude
			this.updateUserLocation(location.latitude, location.longitude)
			this.updateShopMarkers()
		},
		updateShopMarkers() {
			this.markers = this.shops.map(shop => ({
				id: shop.id,
				latitude: shop.latitude,
				longitude: shop.longitude,
				iconPath: shop.id === this.selectedMarkerId ? 
					'/static/位置 拷贝 4@2x.png' : '/static/定位2@2x.png',
				width: 24,
				height: 24,
				zIndex: 3
			}))
		},
		onMapRegionChange(e) {
			// 移除地图拖动时更新用户位置的逻辑
			// 用户位置只跟随实际定位变化
		},
		onMarkerTap(e) {
			const markerId = Number(e.markerId)
			if (markerId === 998) return
			
			if (markerId === 999) {
				uni.navigateTo({
					url: '/packagesUpkeep/WeiXiuMenDian/WeiXiuMenDian'
				})
				return
			}
			
			const shop = this.shops.find(shop => shop.id === markerId)
			if (shop) {
				this.selectedMarkerId = shop.id  // 更新选中的标记
				this.updateShopMarkers()  // 更新标记图标
				this.currentShop = shop
				this.showShopInfo = true
			}
		},
		searchNearbyShops() {
			uni.showToast({
				title: '搜索附近门店...',
				icon: 'none'
			})
			// 这里可以添加实际的搜索逻辑
		},
		contactShop() {
			if (!this.currentShop.phone) {
				uni.showToast({
					title: '商户电话不存在',
					icon: 'none'
				})
				return
			}
			this.showCallPopup = true  // 显示呼叫弹窗
		},
		bookService() {
			// 跳转到门店详情页面，并传递必要的参数
			uni.navigateTo({
				url: `/packagesUpkeep/MenDianDetail/MenDianDetail?id=${this.currentShop.id}&name=${this.currentShop.name}&address=${this.currentShop.address}&image=${this.currentShop.image}&businessHours=${this.currentShop.businessHours}&phone=${this.currentShop.phone}&score=${this.currentShop.score}`
			});
		},
		handleCopy() {
			uni.setClipboardData({
				data: this.currentShop.phone,
				success: () => {
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					})
					this.showCallPopup = false
				}
			})
		},
		handleCall() {
			uni.makePhoneCall({
				phoneNumber: this.currentShop.phone,
				fail: () => {
					uni.showToast({
						title: '拨打电话失败',
						icon: 'none'
					})
				},
				complete: () => {
					this.showCallPopup = false
				}
			})
		},
		handleCancel() {
			this.showCallPopup = false
		},
		onUnload() {
			// 页面卸载时停止位置监听
			uni.stopLocationUpdate()
		},
		showNearestShop() {
			// 按距离排序商铺
			const sortedShops = [...this.shops].sort((a, b) => {
				const distanceA = parseFloat(a.distance.replace('km', ''))
				const distanceB = parseFloat(b.distance.replace('km', ''))
				return distanceA - distanceB
			})
			
			// 显示最近的商铺信息
			if (sortedShops.length > 0) {
				this.currentShop = sortedShops[0]
				this.showShopInfo = true  // 确保显示弹窗
			}
		},
		startNavigation() {
			// 跳转到导航页面，并传递必要的参数
			uni.navigateTo({
				url: `/packagesMap/navigation/navigation?name=${this.currentShop.name}&address=${this.currentShop.address}&latitude=${this.currentShop.latitude}&longitude=${this.currentShop.longitude}`
			})
		}
	}
}
</script>

<style>
.container {
	height: 100vh;
	background: #f5f5f5;
	position: relative;
	overflow: hidden;
}

.blue-bg {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 360rpx;
	background-color: #2979ff;
}

.content {
	position: relative;
	z-index: 1;
	padding: 32rpx;
	height: 100%;
}

.map-card {
	width: 100%;
	height: 100%;
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.map-wrapper {
	padding: 32rpx;
	height: 100%;
}

.map {
	width: 100%;
	height: 100%;
	border-radius: 20rpx;
}

/* 店铺信息弹窗样式 */
.shop-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	z-index: 100;
	padding: 0rpx 24rpx 24rpx 32rpx;
}

.shop-info {
	width: 100%;
}

.shop-main {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 24rpx;
	position: relative;
}

.shop-content {
	flex: 1;
}

.shop-header {
	display: flex;
	align-items: flex-end;
}

.shop-name {
	font-size: 32rpx;
	color: #333;
	text-align: center;
	padding: 20rpx 42rpx;
}

.shop-distance {
	font-size: 26rpx;
	color: #2979ff;
	line-height: 1;
	position: absolute;
	right: 65rpx;
	top: 20rpx;
	
}

.shop-image {
	width: 160rpx;
	height: 120rpx;
	border-radius: 6rpx;
	position: absolute;
	right: 65rpx;
	top: 80rpx;
}

.rating {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
	margin-top: -8rpx;  /* 添加负的上边距，进一步减少间距 */
	padding-left: 40rpx;
}

.score {
	font-size: 24rpx;
	color: #666;
	margin-left: 8rpx;
}

.shop-info-item {
	font-size: 22rpx;
	color: #666;
	margin-bottom: 26rpx;
	line-height: 1.3;
	padding-left: 40rpx;
}

.action-buttons {
	display: flex;
	gap: 16rpx;
	padding: 0 32rpx;  /* 增加左右内边距 */
	width: 85%;       /* 设置宽度为父容器的85% */
	margin: 0 auto;   /* 水平居中 */
}

.contact-btn,
.book-btn {
	flex: 1;
	height: 72rpx;
	border-radius: 36rpx;
	font-size: 26rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	min-width: 240rpx;  /* 设置最小宽度 */
}

.contact-btn {
	background: linear-gradient(to right, #4586FF, #2976FF);
	color: #fff;
}

.book-btn {
	background: linear-gradient(to right, #FF7A59, #FF5B35);
	color: #fff;
}

.btn-icon {
	width: 24rpx;
	height: 24rpx;
	margin-right: 6rpx;
}

/* 地图容器样式 */
.map-wrapper {
	padding: 32rpx;
	height: 100%;
}

.map {
	width: 100%;
	height: 100%;
	border-radius: 20rpx;
}

.location-tip,
.tip-content {
	display: none;
}

.call-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	top: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
}

.call-content {
	width: 100%;
	background: #fff;
	padding: 0;
}


.phone-number {
	font-size: 36rpx;
	color: #333;
	text-align: center;
	padding: 40rpx 32rpx;
	border-bottom: 1rpx solid #eee;
}

/* 添加电话号码点击效果 */
.phone-number:active {
	background: #f5f5f5;
}

.action-list {
	display: flex;
	flex-direction: column;
}

.action-item {
	height: 110rpx;
	line-height: 110rpx;
	text-align: center;
	font-size: 32rpx;
	color: #333;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.cancel {
	margin-top: 20rpx;
	border-bottom: none;
}

/* 点击效果 */
.action-item:active {
	background: #f5f5f5;
}
</style>
